package com.myapp.web.servlet.upload;

import org.apache.commons.fileupload.ProgressListener;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.proxy.ScriptProxy;

@SuppressWarnings("deprecation")
public class UploadProgressListener implements ProgressListener {

	private WebContext wctx = null;
	
	private ScriptProxy scriptProxy = null;

	private ProgressInfo progressInfo = null;

	private boolean reverseAjax = false;
	
	public UploadProgressListener() {
		wctx = WebContextFactory.get();
	}
	
	public void setActiveReverseAjax(boolean reverseAjax){
		this.reverseAjax = reverseAjax;
	}
	
	public UploadProgressListener(ProgressInfo progressInfo) {
		this.progressInfo = progressInfo;
	}

	public void update(long pBytesRead, long pContentLength, int pItems) {
		if(scriptProxy == null && reverseAjax){
			scriptProxy = new ScriptProxy(wctx.getScriptSessionsByPage(wctx.getCurrentPage()));
		}
		
		progressInfo.setBytesRead(pBytesRead);
		progressInfo.setFileIndex(pItems);
		progressInfo.setTotalSize(pContentLength);
		
		if(reverseAjax){
			scriptProxy.addFunctionCall("updateProgress", progressInfo);
		}
	}

	public void inital(){	
		
	}
}
